package com.desire.redis;

import cn.hutool.core.util.StrUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@SpringBootTest
public class Redis_SetNX {
    @Resource(name = "redisTemplate")
    private ValueOperations<String, String> valueOperations;

    @Test
    void setNx() throws InterruptedException {
        String key = "product$01";
        // 创建 缓存线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.execute(() -> {
                // setIfAbsent 相当于redis 原生的 setnx （set not exits）
                // 如果key不存在，则设置key以保存字符串value
                Boolean b = valueOperations.setIfAbsent(key, "wms#01");
                if (b) {
                    System.out.println(StrUtil.format("Thread{} -> success", Thread.currentThread().getName()));
                } else {
                    System.out.println(StrUtil.format("Thread{} -> fail", Thread.currentThread().getName()));
                }
            });
        }
        Thread.sleep(10 * 1000);
    }
}
